package com.test.base.nio1.workertest;

import com.test.utils.ByteBufferUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MutiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        Selector boss = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        SelectionKey sscKey = ssc.register(boss, 0, null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        // 绑定host
        ssc.socket().bind(new InetSocketAddress("127.0.0.1", 8080));

        // 创建worker
        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        AtomicInteger index = new AtomicInteger(0);

        while (true) {
            /*
            使用worker的代码逻辑是，boss来进行accept的检测，检测到的channel绑定注册到worker，然后worker进行处理
             */
            boss.select();
            // keys迭代器
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            // 处理所有的迭代器
            while (iter.hasNext()) {
                // 获取key对象
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel client = ssc.accept();
                    client.configureBlocking(false);
                    log.info("connected{}", client.getRemoteAddress());
                    // 加入到worker当中
                    log.info("before registering {}", client.getRemoteAddress());
                    workers[index.getAndIncrement() % workers.length].register(client);
                    log.info("after register {}", client.getRemoteAddress());
                }
            }
        }
    }

    @Data
    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;
        private ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();


        public Worker(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    // 先进行等待
                    selector.select();
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    // 多线程支持，添加对task任务的使用执行
                    Runnable task = tasks.poll();
                    if (task != null) {
                        task.run(); // 执行一次sc.register(selector, SelectionKey.OP_READ, null);，其中sc为Worker::register方法中加入的参数
                    }
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        // 检测可读性质，只对可读进行操作
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.info("read {}", channel.getRemoteAddress());
                            int read = channel.read(buffer);
                            if (read > 0) {
                                buffer.flip();
                                ByteBufferUtil.debugAll(buffer);
                            } else {
                                key.cancel();
                            }
                        }
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                thread = new Thread(this, name);
                selector = Selector.open();
                // 配置结束后才run
                thread.start();
                start = true;
            }
            tasks.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace(System.err);
                }
            });
            selector.wakeup();

        }

    }
}
